package com.aws.one;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: libugu@cskaoyan.com
 * @date 2024/1/15 - 10:32
 */
@Slf4j
@Component
public class UploadTest {
    @Autowired
    AmazonS3 amazonS3;
    String filePath = "C:\\Users\\libugu\\Desktop\\图片\\01270001.png";

    // 桶是否存在
    public void test() {
        boolean mylibugu = amazonS3.doesBucketExistV2("mylibugu");
        log.info("是否存在：{}", mylibugu);

        try {
            File file = new File(filePath);
            String key = file.getName();  // 使用文件名作为S3对象的键

            PutObjectRequest request = new PutObjectRequest("mylibugu", key, file);
            PutObjectResult putObjectResult = amazonS3.putObject(request);


            System.out.println("File uploaded successfully.");
        } catch (SdkClientException e) {
            System.out.println("完犊子失败了");
        }
    }


    // 文件
    public void test2() {
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.addUserMetadata("test", "test");
        try {
            File file = new File(filePath);
            String e = "aaaa";

            String e3 = file.getName() + ".xlsx";
            String key = e+e3;  // 使用文件名作为S3对象的键
            PutObjectRequest request = new PutObjectRequest("mylibugu", key, file);
            request.setMetadata(objectMetadata);
            amazonS3.putObject(request);
            System.out.println("File uploaded successfully.");
        } catch (SdkClientException e) {
            System.out.println("完犊子失败了");
        }
    }

    // 流
    public void test3() {
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.addUserMetadata("test", "test");
        FileInputStream fileInputStream = null;
        try {
            File file = new File(filePath);
            fileInputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest("mylibugu", "kaka", fileInputStream, objectMetadata);
            amazonS3.putObject(putObjectRequest);
            System.out.println("File uploaded successfully.");
        } catch (SdkClientException e) {
            System.out.println("完犊子失败了");
        }
    }

    // 分段
    public void test4() {
        InitiateMultipartUploadRequest initiateMultipartUploadRequest = new InitiateMultipartUploadRequest("mylibugu", "bububu");

        InitiateMultipartUploadResult initResult = amazonS3.initiateMultipartUpload(initiateMultipartUploadRequest);

        File file = new File(filePath);
        long fileLength = file.length();
        long partSize = 3 * 1024 * 1024;
        long filePosition = 0;
        List<PartETag> partETags = new ArrayList<>();
        UploadPartRequest upRequest = new UploadPartRequest();
        upRequest.setBucketName("mylibugu");
        upRequest.setKey("bububu");
        upRequest.setFile(file);
        upRequest.setUploadId(initResult.getUploadId());
        for (int i = 0; filePosition < fileLength; i++) {

            partSize = Math.min(partSize, (fileLength - filePosition));
            upRequest.setPartNumber(i);
            upRequest.setFileOffset(filePosition);
            upRequest.setPartSize(partSize);
            try {
                UploadPartResult uploadPartResult = amazonS3.uploadPart(upRequest);
                partETags.add(uploadPartResult.getPartETag());
            } catch (SdkClientException e) {
                log.debug("完犊子，异常了：{}", e.getMessage());
            }
            filePosition += partSize;
        }


        CompleteMultipartUploadRequest compRequest = new CompleteMultipartUploadRequest("mylibugu", "bububu", initResult.getUploadId(), partETags);
        amazonS3.completeMultipartUpload(compRequest);

        System.out.println("分段上传完成 666666");
    }


    // 分段
    public void test5() {

        InitiateMultipartUploadRequest initiateRequest = new InitiateMultipartUploadRequest("mylibugu", "qiqi.zip");
        InitiateMultipartUploadResult initResult = amazonS3.initiateMultipartUpload(initiateRequest);
        String uploadId = initResult.getUploadId();

        try {
            // 设置每个分段的大小，这里设置为5MB
            long partSize = 3 * 1024 * 1024;

            // 打开zip文件并获取文件长度
            RandomAccessFile file = new RandomAccessFile(filePath, "r");
            long fileLength = file.length();

            // 计算需要多少个分段
            int totalParts = (int) Math.ceil((double) fileLength / partSize);

            // 初始化用于保存每个分段上传结果的列表
            List<PartETag> partETags = new ArrayList<>();

            // 循环进行每个分段的上传
            for (int partNumber = 1; partNumber <= totalParts; partNumber++) {
                long start = (partNumber - 1) * partSize;
                long end = Math.min(start + partSize, fileLength);
                long size = end - start;
                // 将RandomAccessFile对象转换为InputStream
                InputStream inputStream = new FileInputStream(file.getFD());
                inputStream.skip(start);

                UploadPartRequest uploadRequest = new UploadPartRequest()
                        .withBucketName("mylibugu")
                        .withKey("qiqi.zip")
                        .withUploadId(uploadId)
                        .withPartNumber(partNumber)
                        .withInputStream(inputStream)
                        .withPartSize(size);

                // 上传分段
                UploadPartResult uploadResult = amazonS3.uploadPart(uploadRequest);
                partETags.add(uploadResult.getPartETag());
            }

            // 完成分段上传
            CompleteMultipartUploadRequest completeRequest = new CompleteMultipartUploadRequest("mylibugu", "qiqi.zip", uploadId, partETags);
            amazonS3.completeMultipartUpload(completeRequest);

            System.out.println("分段上传完成");
        } catch (Exception e) {
            // 异常处理
            System.err.println("分段上传失败：" + e.getMessage());
            AbortMultipartUploadRequest abortRequest = new AbortMultipartUploadRequest("mylibugu", "qiqi.zip", uploadId);
            amazonS3.abortMultipartUpload(abortRequest);
        }
    }
}
